<template>
  <div class="sightings-management">
    <div class="page-header">
      <h2>线索管理</h2>
      <div class="header-actions">
        <el-select
          v-model="filters.is_verified"
          placeholder="验证状态"
          clearable
          style="width: 120px; margin-right: 10px"
          @change="fetchSightings"
        >
          <el-option label="已验证" :value="true" />
          <el-option label="未验证" :value="false" />
        </el-select>

        <el-button @click="fetchSightings" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-card>
      <el-table
        :data="sightings"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="相关帖子" width="200">
          <template #default="{ row }">
            <div class="post-info">
              <div class="post-title">{{ row.post_info.title }}</div>
              <div class="post-details">
                发布者: {{ row.post_info.owner_username }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sighting_location" label="目击地点" width="150" />

        <el-table-column label="目击时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.sighting_time) }}
          </template>
        </el-table-column>

        <el-table-column label="是否有照片" width="100">
          <template #default="{ row }">
            <el-tag :type="row.sighting_photo_url ? 'success' : 'info'">
              {{ row.sighting_photo_url ? '有照片' : '无照片' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="验证状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_verified ? 'success' : 'warning'">
              {{ row.is_verified ? '已验证' : '未验证' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="提交者IP" width="120">
          <template #default="{ row }">
            <span class="ip-address">{{ row.reporter_ip || '未知' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="提交时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewSighting(row)">
              查看详情
            </el-button>
            <el-popconfirm
              title="确定要删除这条线索吗？"
              @confirm="deleteSighting(row)"
            >
              <template #reference>
                <el-button size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 线索详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="线索详情"
      width="600px"
    >
      <div v-if="selectedSighting" class="sighting-detail">
        <div class="detail-section">
          <h4>相关帖子信息</h4>
          <p><strong>帖子标题：</strong>{{ selectedSighting.post_info.title }}</p>
          <p><strong>宠物名字：</strong>{{ selectedSighting.post_info.pet_name }}</p>
          <p><strong>宠物品种：</strong>{{ selectedSighting.post_info.pet_species }}</p>
          <p><strong>宠物颜色：</strong>{{ selectedSighting.post_info.pet_color }}</p>
          <p><strong>发布者：</strong>{{ selectedSighting.post_info.owner_username }}</p>
        </div>

        <div class="detail-section">
          <h4>目击信息</h4>
          <p><strong>目击地点：</strong>{{ selectedSighting.sighting_location }}</p>
          <p><strong>目击时间：</strong>{{ formatDate(selectedSighting.sighting_time) }}</p>
          <p><strong>验证状态：</strong>
            <el-tag :type="selectedSighting.is_verified ? 'success' : 'warning'">
              {{ selectedSighting.is_verified ? '已验证' : '未验证' }}
            </el-tag>
          </p>
          <p><strong>提交时间：</strong>{{ formatDate(selectedSighting.created_at) }}</p>
          <p><strong>提交者IP：</strong>{{ selectedSighting.reporter_ip || '未知' }}</p>
        </div>

        <div v-if="selectedSighting.description" class="detail-section">
          <h4>描述信息</h4>
          <p>{{ selectedSighting.description }}</p>
        </div>

        <div v-if="selectedSighting.sighting_photo_url" class="detail-section">
          <h4>目击照片</h4>
          <img
            :src="getFullImageUrl(selectedSighting.sighting_photo_url)"
            class="sighting-photo"
            alt="目击照片"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-popconfirm
          title="确定要删除这条线索吗？"
          @confirm="deleteSighting(selectedSighting)"
        >
          <template #reference>
            <el-button type="danger">删除线索</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getAllSightings, deleteSighting as deleteSightingApi, type Sighting } from '@/api/sightings'
import { getFullImageUrl } from '@/utils/helpers'
import dayjs from 'dayjs'

const sightings = ref<Sighting[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filters = reactive({
  is_verified: undefined as boolean | undefined
})

const detailDialogVisible = ref(false)
const selectedSighting = ref<Sighting | null>(null)

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('MM-DD HH:mm')
}

// 获取线索列表
const fetchSightings = async () => {
  loading.value = true

  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value
    }

    if (filters.is_verified !== undefined) {
      params.is_verified = filters.is_verified
    }

    const response = await getAllSightings(params)

    sightings.value = response.data
    total.value = response.pagination.totalItems

  } catch (error) {
    console.error('获取线索列表失败:', error)
    ElMessage.error('获取线索列表失败')
  } finally {
    loading.value = false
  }
}

// 查看线索详情
const viewSighting = (sighting: Sighting) => {
  selectedSighting.value = sighting
  detailDialogVisible.value = true
}

// 删除线索
const deleteSighting = async (sighting: Sighting | null) => {
  if (!sighting) return

  try {
    await deleteSightingApi(sighting.id)
    ElMessage.success('线索删除成功')

    // 从列表中移除已删除的线索
    const index = sightings.value.findIndex(s => s.id === sighting.id)
    if (index > -1) {
      sightings.value.splice(index, 1)
      total.value--
    }

    // 如果是在详情对话框中操作，关闭对话框
    if (detailDialogVisible.value) {
      detailDialogVisible.value = false
    }

  } catch (error) {
    console.error('删除线索失败:', error)
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchSightings()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchSightings()
}

onMounted(() => {
  fetchSightings()
})
</script>

<style scoped>
.sightings-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.post-info {
  line-height: 1.4;
}

.post-title {
  font-weight: bold;
  margin-bottom: 2px;
}

.post-details {
  font-size: 12px;
  color: #666;
}

.ip-address {
  font-family: monospace;
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.sighting-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.detail-section p {
  margin: 5px 0;
  line-height: 1.5;
}

.sighting-photo {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  object-fit: contain;
}
</style>
